package com.hbut.system.service.sysuser.imp;

import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hbut.common.core.constants.HttpConstants;
import com.hbut.common.core.domain.LoginUser;
import com.hbut.common.core.domain.R;
import com.hbut.common.core.domain.vo.LoginUserVO;
import com.hbut.common.core.enums.ResultCode;
import com.hbut.common.core.enums.UserIdentity;
import com.hbut.common.security.exception.ServiceException;
import com.hbut.common.security.service.TokenService;
import com.hbut.system.domain.sysuser.dto.LoginDTO;
import com.hbut.system.domain.sysuser.SysUser;
import com.hbut.system.domain.sysuser.dto.SysUserSaveDTO;
import com.hbut.system.mapper.sysuser.SysUserMapper;
import com.hbut.system.service.sysuser.ISysUserService;
import com.hbut.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RefreshScope
public class ISysUserServiceImp implements ISysUserService {
    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    /**
     * 用户登录
     *
     * @param loginDTO 登录信息
     * @return 登录结果
     */
    @Override
    public R<String> login(LoginDTO loginDTO) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId,SysUser::getPassword,SysUser::getNickName)
                .eq(SysUser::getUserAccount,loginDTO.getUserAccount()));
        if(sysUser == null){
            // 用户不存在
            return R.fail(ResultCode.FAILED_NOT_EXISTS);
        } else if (!BCryptUtils.matchesPassword(loginDTO.getPassword(),sysUser.getPassword())) {
            // 密码错误
            return R.fail(ResultCode.FAILED_LOGIN);
        }else{
          return R.ok(tokenService.createToken(sysUser.getUserId(),UserIdentity.ADMIN.getValue(), secret,sysUser.getNickName(),null));
        }
    }

    @Override
    public boolean logout(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.logout(token,secret);
    }

    @Override
    public R<LoginUserVO> info(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if (loginUser == null) {
            return R.fail(ResultCode.FAILED_UNAUTHORIZED);
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return R.ok(loginUserVO);
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        List<SysUser> sysUserList = sysUserMapper.selectList(queryWrapper
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getAccount()));
        if(CollectionUtils.isNotEmpty(sysUserList)){
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        sysUser.setCreateBy(100L);
        sysUser.setCreateTime(LocalDateTime.now());
        return sysUserMapper.insert(sysUser);
    }




}
